package com.cuit.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.Map;

@Slf4j
public class JWTUtils {

    private static final String SING = "chenfuyou!@#$%^";
    /**
     * 生成token
     */
    public static String getToKen(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,1) ; // 默认七天过期
        JWTCreator.Builder builder = JWT.create();

        map.forEach((k,v )->{
            builder.withClaim(k,v);
        });
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));

        return token;
    }
    /**
     * 验证token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }
    /**
     * 获取信息
     */
    public static DecodedJWT getTokenInfo(String token){
        try {
            return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        }catch (ExpiredJwtException e) {
            log.error("JWT过期：", e);
            throw new RuntimeException("JWT过期");
        } catch (UnsupportedJwtException e) {
            log.error("不支持的JWT：", e);
            throw new RuntimeException("不支持的JWT");
        } catch (MalformedJwtException e) {
            log.error("JWT格式错误：", e);
            throw new RuntimeException("JWT格式错误");
        } catch (SignatureException e) {
            log.error("签名异常：", e);
            throw new RuntimeException("签名异常");
        } catch (IllegalArgumentException e) {
            log.error("非法请求：", e);
            throw new RuntimeException("非法请求");
        } catch (Exception e) {
            log.error("解析异常：", e);
            throw new RuntimeException("解析异常");
        }
    }
}
